package com.flute.icrawler.app.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.flute.icrawler.app.util.ParameterKey;
import com.flute.tools.data.DataRecord;
import com.flute.tools.data.berkeleydb.BerkeleyDatabase;

public class BerkeleyDatabaseService {
	private BerkeleyDatabase berkeleyDatabase = null;

	private static final Logger LOGGER = LoggerFactory
			.getLogger(BerkeleyDatabaseService.class);

	private static BerkeleyDatabaseService service = null;

	private BerkeleyDatabaseService() {
		berkeleyDatabase = new BerkeleyDatabase(
				ParameterKey.RESULT_BDB_ENV_NAME,
				ParameterKey.RESULT_BDB_DB_NAME, null, null);
	}

	public static BerkeleyDatabaseService getInstance() {
		if (null == service) {
			service = new BerkeleyDatabaseService();
		}
		return service;
	}

	/**
	 * 记录抓取数据的相关信息 包括链接名 存储的网页文件所在路径
	 * 
	 * @param crawlDataRecord
	 */
	public synchronized void addDataRecord(DataRecord dataRecord) {

		berkeleyDatabase.push(dataRecord
				.getFieldValue(ParameterKey.COLUMN_CREATE_TIME), dataRecord);
		berkeleyDatabase.flush();
		LOGGER.info("BerkeleyDatabaseService save ok"
				+ dataRecord.getFieldValue(ParameterKey.COLUMN_CREATE_TIME) + "->"
				+ dataRecord);

	}

	public void close() {
		if (berkeleyDatabase != null) {
			berkeleyDatabase.close();
		}
	}
}
